package net.openl10n.packaging;

import java.util.Iterator;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.collect.ImmutableList.Builder;

public class AnnotationSourceImpl implements AnnotationSource{

	private final Multimap<Class<?>, Object> annotations = HashMultimap.create();;
	
	@Override
	public <T> T getAnnotation(Class<T> clz){
		if(clz == null)
			throw new IllegalArgumentException("clz");
		Iterator<Object> it = annotations.get(clz).iterator();
		if(it.hasNext()){
			return clz.cast(it.next());
		}
		return null;
	}
	
	@Override
	public <T> ImmutableList<T> getAnnotations(Class<T> clz){
		if(clz == null)
			throw new IllegalArgumentException("clz");
		Iterator<Object> it = annotations.get(clz).iterator();
		Builder<T> builder = ImmutableList.builder();
		while(it.hasNext()){
			builder.add(clz.cast(it.next()));
		}
		return builder.build();
	}

	@Override
	public <T> void addAnnotation(T annotation){
		if(annotation == null)
			throw new IllegalArgumentException("annotation");
		annotations.put(annotation.getClass(), annotation);
	}
	
	@Override
	public <T> void addAnnotation(Class<? super T> clz, T annotation) {
		if(annotation == null)
			throw new IllegalArgumentException("annotation");
		if(clz == null)
			throw new IllegalArgumentException("clz");
		annotations.put(clz, annotation);
		
	};
	
	@Override
	public <T> void removeAnnotation(T annotation) {
		if(annotation == null)
			throw new IllegalArgumentException("clz");
		annotations.remove(annotation.getClass(), annotation);
		
	};
	
	@Override
	public <T> void removeAnnotations(Class<T> clz) {
		if(clz == null)
			throw new IllegalArgumentException("clz");
		annotations.removeAll(clz);
		
	}
}
